package com.s63.modules.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.s63.entity.Menu;
import com.s63.entity.Role;
import com.s63.entity.User;
import com.s63.service.IMenuService;
import com.s63.service.IRoleService;
import com.s63.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
//    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /**
         * 1、根据用户名查询用户
         * 2、查询用户对应的角色
         * 3、查询用户对应的权限
         */
        //1.
        if (log.isDebugEnabled()) {
            log.debug("用户开始登录:{}", username);
        }
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, username));
        if (user == null) {
            log.error("用户不存在:{}", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        //2.
        List<Role> roleList = roleService.listByUserId(user.getUserId());
        //3.
        List<Menu> menuList = menuService.listByUserId(user.getUserId());

        LoginUser loginUser = new LoginUser();
        loginUser.setRoleKeyList(roleList.stream().map(Role::getRoleKey).collect(Collectors.toList()));
        loginUser.setPermsList(new ArrayList<>(menuList.stream().filter(menu -> StringUtils.hasText(menu.getPerms())).map(Menu::getPerms).collect(Collectors.toSet())));
        loginUser.setUser(user);
        if (log.isDebugEnabled()) {
            log.debug("roleKeyList:{}", loginUser.getRoleKeyList());
            log.debug("permsList:{}", loginUser.getPermsList());
            log.debug("userId:{}, userName:{}, nickName:{}", user.getUserId(), username, user.getNickName());
        }
        return loginUser;
    }
}
